<template>
  <div id="fill-insurance-detail">
    <navbar v-model="packageSelected" class="nav">
      <tab-item id="1" class="item">经济型</tab-item>
      <tab-item id="2" class="item">全面型</tab-item>
      <tab-item id="3" class="item">豪华型</tab-item>
      <tab-item id="4" class="item">自定义</tab-item>
    </navbar>

    <insurance-type-header
      title="商业险"
      tip="*需要不计免赔请点击 “免” 字"
      color="blue"></insurance-type-header>

    <grey-header title="基本险"></grey-header>

    <ul>
      <li
        class="checkbox-li"
        v-for="(item, index) in items[packageSelected - 1].basic"
        :key="index">
        <div class="checkbox-wrap" @click="clickCheckbox('basic'+'-'+packageSelected+'-'+index)">
          <input
            @click.stop="changeNRCheckbox('basic'+'-'+packageSelected+'-'+index+'-NR', {id: item.id, name: item.name, insured_value: item.insured_value}, item.id, 'basic')"
            :id="'basic'+'-'+packageSelected+'-'+index"
            :disabled="packageSelected !== '4'"
            type="checkbox"
            v-model="basicCheckboxList[packageSelected - 1]"
            :value="{id: item.id, name: item.name, insured_value: item.insured_value}">
          <h3>{{ item.name }}</h3>
        </div>

        <select
          v-model="basicSelects[packageSelected - 1][item.id]"
          v-if="typeof item.insured_value === 'object' && item.insured_value[0] !== ''"
          class="value">
          <option :value="undefined" disabled>请选择</option>
          <option
            v-for="(optionItem, optionIndex) in item.insured_value"
            :key="optionIndex"
            :value="optionItem">{{ optionItem | formatTenThousand }}</option>
        </select>
        <!-- 这种情况用 item.insured_value 取 -->
        <h4 class="value" v-else-if="packageSelected !== '4'">{{ item.insured_value | formatTenThousand }}</h4>
        <input
          :id="'basic'+'-'+packageSelected+'-'+index+'-NR'"
          :disabled="packageSelected !== '4'"
          v-if="item.deductible === '1'"
          type="checkbox"
          :value="item.id"
          v-model="basicNRCheckboxList[packageSelected - 1]">
      </li>
    </ul>

    <grey-header title="附加险"></grey-header>

    <ul>
      <li
        class="checkbox-li"
        v-for="(item, index) in items[packageSelected - 1].others"
        :key="index">
        <div class="checkbox-wrap" @click="clickCheckbox('others'+'-'+packageSelected+'-'+index)">
          <input
            @click.stop="changeNRCheckbox('others'+'-'+packageSelected+'-'+index+'-NR', {id: item.id, name: item.name, insured_value: item.insured_value}, item.id, 'others')"
            :id="'others'+'-'+packageSelected+'-'+index"
            :disabled="packageSelected !== '4'"
            type="checkbox"
            v-model="othersCheckboxList[packageSelected - 1]"
            :value="{id: item.id, name: item.name, insured_value: item.insured_value}">
          <h3>{{ item.name }}</h3>
        </div>
        <select
          v-model="othersSelects[packageSelected - 1][item.id]"
          v-if="typeof item.insured_value === 'object' && item.insured_value[0] !== ''"
          class="value">
          <option :value="undefined" disabled>请选择</option>
          <option
            v-for="(optionItem, optionIndex) in item.insured_value"
            :key="optionIndex"
            :value="optionItem === '国产' ? 1 : (optionItem === '进口' ? 2 : optionItem)">{{ optionItem | formatTenThousand }}</option>
        </select>
        <h4 class="value" v-else-if="packageSelected !== '4'">{{ item.insured_value | formatTenThousand }}</h4>
        <input
          :id="'others'+'-'+packageSelected+'-'+index+'-NR'"
          :disabled="packageSelected !== '4'"
          v-if="item.deductible === '1'"
          type="checkbox"
          :value="item.id"
          v-model="othersNRCheckboxList[packageSelected - 1]">
      </li>
    </ul>

    <insurance-type-header
      class="compulsory"
      title="交强险"
      tip="*交强险包含车船税"
      color="red"></insurance-type-header>

    <ul>
      <li
        class="checkbox-li"
        v-for="(item, index) in items[packageSelected - 1].compulsory"
        :key="index">
        <div class="checkbox-wrap" @click="clickCheckbox('compulsory'+'-'+packageSelected+'-'+index)">
          <input
            @click.stop="changeNRCheckbox('compulsory'+'-'+packageSelected+'-'+index+'-NR', {id: item.id, name: item.name, insured_value: item.insured_value}, item.id, 'compulsory')"
            :id="'compulsory'+'-'+packageSelected+'-'+index"
            :disabled="packageSelected !== '4'"
            type="checkbox"
            v-model="compulsoryCheckboxList[packageSelected - 1]"
            :value="{id: item.id, name: item.name, insured_value: item.insured_value}">
          <h3>{{ item.name }}</h3>
        </div>
        <select
          v-model="compulsorySelects[packageSelected - 1][item.id]"
          v-if="typeof item.insured_value === 'object' && item.insured_value[0] !== ''"
          class="value">
          <option :value="undefined" disabled>请选择</option>
          <option
            v-for="(optionItem, optionIndex) in item.insured_value"
            :key="optionIndex"
            :value="optionItem">{{ optionItem | formatTenThousand }}</option>
        </select>
        <h4 class="value" v-else-if="packageSelected !== '4'">{{ item.insured_value | formatTenThousand }}</h4>
        <input
          :id="'compulsory'+'-'+packageSelected+'-'+index+'-NR'"
          :disabled="packageSelected !== '4'"
          v-if="item.deductible === '1'"
          type="checkbox"
          :value="item.id"
          v-model="compulsoryNRCheckboxList[packageSelected - 1]">
      </li>
    </ul>

    <footer class="public-footer-btn-box">
      <button
        class="single-button"
        :disabled="submitDisabled"
        @click="confirm">确定</button>
    </footer>
  </div>
</template>

<script>
  import { Toast, Navbar, TabItem } from 'mint-ui';
  import GreyHeader from './grey-header.vue';
  import InsuranceTypeHeader from './insurance-type-header.vue';
  export default {
    name: "fill-insurance-detail",
    components: {
      Navbar,
      TabItem,
      InsuranceTypeHeader,
      GreyHeader
    },
    data() {
      return {
        packageSelected: '4',

        // 所有套餐信息

        packages: [],

        // 按套餐(细分经济、全面、豪华、自定义) 归类 险种(细分基本、附加、交强) 信息 用于展示

        items: [
          {
            basic: [],
            others: [],
            compulsory: []
          },
          {
            basic: [],
            others: [],
            compulsory: []
          },
          {
            basic: [],
            others: [],
            compulsory: []
          },
          {
            basic: [],
            others: [],
            compulsory: []
          }
        ],

        // 基本险(细分经济、全面、豪华、自定义) 用于获取参数

        basicCheckboxList: {
          0: [],
          1: [],
          2: [],
          3: []
        },
        basicNRCheckboxList: {
          0: [],
          1: [],
          2: [],
          3: []
        },
        basicSelects: {
          0: {},
          1: {},
          2: {},
          3: {}
        },

        // 附加险(细分经济、全面、豪华、自定义) 用于获取参数

        othersCheckboxList: {
          0: [],
          1: [],
          2: [],
          3: []
        },
        othersNRCheckboxList: {
          0: [],
          1: [],
          2: [],
          3: []
        },
        othersSelects: {
          0: {},
          1: {},
          2: {},
          3: {}
        },

        // 交强险(细分经济、全面、豪华、自定义) 用于获取参数

        compulsoryCheckboxList: {
          0: [],
          1: [],
          2: [],
          3: []
        },
        compulsoryNRCheckboxList: {
          0: [],
          1: [],
          2: [],
          3: []
        },
        compulsorySelects: {
          0: {},
          1: {},
          2: {},
          3: {}
        },

        submitDisabled: false
      }
    },
    methods: {

      // 按套餐 获取 险种信息

      getPackage(id) {
        this.$http.post({
          api: this.$api.INSURANCE_PACKAGE,
          params: {
            package_id: id + 1
          },
          success: (res) => {
            this.packages[id] = res.data.data;

            // 处理每一个套餐各自的险种信息

            this.formatPackage(this.packages[id], id);
          }
        });
      },

      // packages => items、处理固定套餐的参数

      formatPackage(arr, id) {
        for (let i = 0; i < arr.length; i++) {

          if (arr[i].type === '1' && arr[i].insured_type === '1') {

            // 基本险

            this.items[id].basic.push(arr[i]);

            if (id !== 3 ) {
              this.basicCheckboxList[id].push({
                id: arr[i].id,
                name: arr[i].name,
                insured_value: arr[i].insured_value});

              if (arr[i].deductible === '1') {
                this.basicNRCheckboxList[id].push(arr[i].id);
              }
            }
          } else if (arr[i].type === '1' && arr[i].insured_type === '2') {

            // 附加险

            this.items[id].others.push(arr[i]);

            if (id !== 3 ) {
              this.othersCheckboxList[id].push({
                id: arr[i].id,
                name: arr[i].name,
                insured_value: arr[i].insured_value});

              if (arr[i].deductible === '1') {
                this.othersNRCheckboxList[id].push(arr[i].id);
              }
            }
          } else if (arr[i].type === '2' && arr[i].insured_type === '1') {

            // 交强险

            this.items[id].compulsory.push(arr[i]);

            if (id !== 3 ) {
              this.compulsoryCheckboxList[id].push({
                id: arr[i].id,
                name: arr[i].name,
                insured_value: arr[i].insured_value});

              if (arr[i].deductible === '1') {
                this.compulsoryNRCheckboxList[id].push(arr[i].id);
              }
            }
          }
        }
      },

      // 统计当前套餐的选择、返回参数 (包括验证)

      getParams() {

        // 初始化

        let insurance_info = [],
          packageSelected = this.packageSelected,
          packageIndex = this.packageSelected - 1,
          scratchChose = false;

        // 基本险

        for (let i = 0; i < this.basicCheckboxList[packageIndex].length; i++) {

          if (packageSelected === '4' &&
            this.basicCheckboxList[packageIndex][i].insured_value[0] !== '' &&
            !this.basicSelects[packageIndex][this.basicCheckboxList[packageIndex][i].id]) {
            Toast('请选择' + this.basicCheckboxList[packageIndex][i].name + '的保险档次');
            return false;
          }

          insurance_info.push(
            {
              package_id: packageSelected,
              type: 1,
              insured_type: 1,
              id: this.basicCheckboxList[packageIndex][i].id,
              name: this.basicCheckboxList[packageIndex][i].name,
              insured_value: packageSelected === '4' ?
                this.basicSelects[packageIndex][this.basicCheckboxList[packageIndex][i].id] :
                this.basicCheckboxList[packageIndex][i].insured_value,
              deductible: this.basicNRCheckboxList[packageIndex].indexOf(this.basicCheckboxList[packageIndex][i].id) === -1 ? 2 : 1
            }
          );
        }

        // 附加险

        for (let i = 0; i < this.othersCheckboxList[packageIndex].length; i++) {

          if (packageSelected === '4' &&
            this.othersCheckboxList[packageIndex][i].insured_value[0] !== '' &&
            !this.othersSelects[packageIndex][this.othersCheckboxList[packageIndex][i].id]) {
            Toast('请选择' + this.othersCheckboxList[packageIndex][i].name + '的保险档次');
            return false;
          }
          else if (this.othersCheckboxList[packageIndex][i].name === '划痕险') {
            scratchChose = true;
          }

          insurance_info.push(
            {
              package_id: packageSelected,
              type: 1,
              insured_type: 2,
              id: this.othersCheckboxList[packageIndex][i].id,
              name: this.othersCheckboxList[packageIndex][i].name,
              insured_value: packageSelected === '4' ?
                this.othersSelects[packageIndex][this.othersCheckboxList[packageIndex][i].id] :
                (this.othersCheckboxList[packageIndex][i].insured_value === '国产' ? 1 : (this.othersCheckboxList[packageIndex][i].insured_value === '进口' ? 2 : this.othersCheckboxList[packageIndex][i].insured_value)),
              deductible: this.othersNRCheckboxList[packageIndex].indexOf(this.othersCheckboxList[packageIndex][i].id) === -1 ? 2 : 1
            }
          );
        }

        // 交强险

        for (let i = 0; i < this.compulsoryCheckboxList[packageIndex].length; i++) {

          if (packageSelected === '4' &&
            this.compulsoryCheckboxList[packageIndex][i].insured_value[0] !== '' &&
            !this.compulsorySelects[packageIndex][this.compulsoryCheckboxList[packageIndex][i].id]) {
            Toast('请选择' + this.compulsoryCheckboxList[packageIndex][i].name + '的保险档次');
            return false;
          }

          insurance_info.push(
            {
              package_id: packageSelected,
              type: 2,
              insured_type: 1,
              id: this.compulsoryCheckboxList[packageIndex][i].id,
              name: this.compulsoryCheckboxList[packageIndex][i].name,
              insured_value: packageSelected === '4' ?
                this.compulsorySelects[packageIndex][this.compulsoryCheckboxList[packageIndex][i].id] : this.compulsoryCheckboxList[packageIndex][i].insured_value,
              deductible: this.compulsoryNRCheckboxList[packageIndex].indexOf(this.compulsoryCheckboxList[packageIndex][i].id) === -1 ? 2 : 1
            }
          );
        }

        if (insurance_info.length === 0) {
          Toast('请选择保险种类');
          return false;
        } else if (scratchChose) {

          // 选择了划痕险

          let errorToast = () => {
            Toast('划痕险以车损险为基础');
            return false;
          };

          if (this.basicCheckboxList[packageIndex].length === 0) {
            errorToast();
          }

          for (let i = 0; i < this.basicCheckboxList[packageIndex].length; i++) {

            let insuranceName = this.basicCheckboxList[packageIndex][i].name;
            let length = this.basicCheckboxList[packageIndex].length;

            if (insuranceName !== '车损险' && i < length - 1) {
              continue;
            } else if (insuranceName === '车损险') {
              return {
                // 车主id
                car_owner_id: this.$route.params.car_owner_id,
                // 车辆id
                car_id: this.$route.params.car_id,
                // 保单id
                policy_id: this.$route.params.policy_id,
                // 用户id
                user_id: localStorage.getItem('id'),
                // 套餐id
                package_id: packageSelected,

                // 险种信息
                insurance_info: insurance_info
              }
            }
            errorToast();
            return false;
          }
        } else {
          return {
            // 车主id
            car_owner_id: this.$route.params.car_owner_id,
            // 车辆id
            car_id: this.$route.params.car_id,
            // 保单id
            policy_id: this.$route.params.policy_id,
            // 用户id
            user_id: localStorage.getItem('id'),
            // 套餐id
            package_id: packageSelected,

            // 险种信息
            insurance_info: insurance_info,

            // 险种id (修改时必传)
            in_id: this.$route.query.in_id
          }
        }
      },

      // 提交

      confirm() {
        let params = this.getParams();
        if (params) {

          this.$http.post({
            api: this.$api.INSURANCE_PACKAGE_INFO,
            params: params,
            success: (res) => {

              this.$tool.whenToast(
                () => {
                  // 禁止重复提交 （不再恢复，组件即将销毁）

                  this.submitDisabled = true;
                },
                {
                  message: '提交成功，请继续选择车型',
                  duration: -1,
                  className: 'public-long-toast'
                },
                () => {

                  // 重新把自身的车主、车辆、保单 id 提过去选车型页面

                  this.$router.push({
                    name: 'FillInsuranceCar',
                    params: {
                      type: this.$route.params.type,
                      car_owner_id: this.$route.params.car_owner_id,
                      car_id: this.$route.params.car_id,
                      policy_id: this.$route.params.policy_id,
                      in_id: res.data.data.in_id
                    },
                    query: {
                      insurance_package: this.packageSelected
                    }
                  });
                },2000
              );
            }
          });
        }
      },

      clickCheckbox(id) {
        document.getElementById(id).click();
      },

      changeNRCheckbox(id, checkboxValue, NRCheckboxValue, type) {
        setTimeout(() => {
          let checkboxChecked = false,
            NRCheckboxChecked = this[type + 'NRCheckboxList'][this.packageSelected - 1].indexOf(NRCheckboxValue) !== -1;

          this[type + 'CheckboxList'][this.packageSelected - 1].forEach(function (item, index) {
            if (JSON.stringify(item) === JSON.stringify(checkboxValue)) {
              return checkboxChecked = true;
            }
          });

          if (checkboxChecked !== NRCheckboxChecked) {
            document.getElementById(id) && document.getElementById(id).click();
          }
        }, 300) // 移动端的 click 有300毫秒延迟
      }
    },
    created() {
      for (let i = 0; i< 4; i++) {
        this.getPackage(i);
      }
    },
    activated() {

      this.allDisabled = false;
      this.submitDisabled = false;

      // 当从保单填写页面 进入时 清空自定义套餐的选择

      if (this.$route.query.last_page === 'policy') {

        // 基本险(细分经济、全面、豪华、自定义) 用于获取参数

        this.basicCheckboxList[3] = [];
        this.basicNRCheckboxList[3] = [];
        this.basicSelects[3] = {};

        // 附加险(细分经济、全面、豪华、自定义) 用于获取参数

        this.othersCheckboxList[3] = [];
        this.othersNRCheckboxList[3] = [];
        this.othersSelects[3] = {};

        // 交强险(细分经济、全面、豪华、自定义) 用于获取参数

        this.compulsoryCheckboxList[3] = [];
        this.compulsoryNRCheckboxList[3] = [];
        this.compulsorySelects[3] = {};
      }
    }
  }
</script>

<style lang="scss">

  #fill-insurance-detail {

    padding-bottom: $public-footer-btn-box-height;

    >.nav {
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 7.5rem;
      margin-bottom: 1rem;
      box-shadow: $public-box-shadow;
      border-radius: $public-banner-border-radius;

      >.item {
        flex: none;
        display: flex;
        justify-content: space-around;
        align-items: center;
        width: 20%;
        height: 3rem;
        padding: 0;
        font-size: 1.5rem;
        color: #333;
        box-shadow: $public-box-shadow;
        border-radius: 6px;
      }

      >.is-selected {
        color: $white;
        margin-bottom: 0;
        background: #0097ff;
        border: none;
      }
    }

    >.compulsory {
      margin-top: 1rem;
    }

    >ul {
      padding: 0 .8rem;
      background: $white;

      >.checkbox-li {

        $li-height: 5rem;
        $value-height: 2.3rem;

        position: relative;
        display: flex;
        align-items: center;
        height: $li-height;
        border-bottom: 1px solid #eee;

        >.checkbox-wrap {

          $wrap-size: 2.8rem;

          display: flex;
          justify-content: space-around;
          align-items: center;
          height: $wrap-size;

          >input {

            $input-size: 1.8rem;

            width: $input-size;
            height: $input-size;
            margin: 0 .5rem;
            border: 1px solid #ddd;
            border-radius: $input-size / 2;

            &:checked {
              background: url("../../assets/images/public/tick.png") no-repeat center / $size-as-parent auto;
            }
          }

          >h3 {
            font-size: 1.5rem;
            color: #333;
          }
        }

        >.value {
          position: absolute;
          top: ($li-height - $value-height) / 2;
          right: 2.8rem;
          height: $value-height;
          line-height: $value-height;
        }

        >select {
          -webkit-appearance: none;
          -moz-appearance: none;
          appearance: none;
          width: 6rem;
          padding-left: .8rem;
          background: #f5f5f5;
          border-radius: $value-height / 2;
        }

        >h4 {
          padding-right: 1.8rem;
          font-size: 1.2rem;
          color: #333;
        }

        >input[type=checkbox] {

          $checkbox-size: 2rem;

          position: absolute;
          right: 0;
          top: ($li-height - $checkbox-size) / 2;
          width: $checkbox-size;
          height: $checkbox-size;
          background: url("../../assets/images/public/none-responsibility-unchecked.png") no-repeat center / $size-as-parent $size-as-parent;

          &:checked {
            background: url("../../assets/images/public/none-responsibility-checked.png") no-repeat center / $size-as-parent $size-as-parent;
          }
        }

        &:last-of-type {
          border: none;
        }
      }
    }
  }
</style>
